<template>
	<view>
		<view>
			<view class="travels-wrap">
				<!-- 分类 -->
				<view class="travels">
					<text>分类</text>
					<block v-for="(item,index) in travelsList" :key="index">
						<view :class="{active:index==num}" @click="tabshaddle(index,item.Uname)">
							{{item.Uname}}
						</view>
					</block>
				</view>
				<!-- 标题 -->
				<view class="input-title">
					<input type="text" value="" placeholder="发表旅游标题" v-model="biaotiOne"/>
				</view>

				<!-- nron -->
				<view class="input-neiron">
					<textarea value="" placeholder="把你的旅游心得分享给大家吧!" v-model="biaotiTwo"/>
					</view>
			</view>
		</view>
		
		<!-- 上传照片 -->
		<view class="travels-upload">
			<view class="upload-img">
				<image src="../../static/tab/topimg.png" mode="" @click="uploadImg"></image>
			</view>
			<view>
				<view class="upload-images-night">
					<block v-for="(item,index) in travelsIma":key="index">
						<view style="position: relative;">
							<image :src="item" mode="aspectFill" class="uploadImgs" @click="preImage(index)"></image>
							<image src="../../static/tab/shanchu.png" mode=""class="uploadImgsDelete" @click="ImageDelete(index)"></image>
						</view>
					</block>
				</view>
			</view>
		</view>
		
		<!-- 上传视频 -->
		<view>
			<view class="video-wrap">
				<view><image src="../../static/tab/topvideo.png" mode="" @click="uploadvideo"></image></view>
			</view>
			<view class="video-m" v-if="disp">
				<video :src="video" controls objectFit="cover"></video>
				<image src="../../static/tab/shanchu.png" mode=""class="uploadVideoDelete" @click="VideoeDelete()"></image>
			</view>
		</view>
		
		<!-- 定位服务 -->
		<view class="city-view">
			<view class="city-text">你在这里</view>
			<view class="city-img" @click="myAddres">
				<image src="../../static/tab/gonglveb.png" mode="widthFix"></image>
				<text class="txt">{{myaddre}}</text>
			</view>
		</view>
		
		<!-- 发布按钮 -->
		<view class="fabu-btn" @click="submit">
			<text>发布</text>
		</view>
		
		<!-- 反馈组件 -->
		<HMmessages ref="HMmessages" @complete="HMmessages = $refs.HMmessages" @clickMessage="clickMessage"></HMmessages>
		
		<!-- 模态框 -->
		<motai ref="mon"></motai>
		
	</view>
</template>

<script>
	//上传图片分装
	import packmages from '../../element/images.js'
	//定位服务
	import addresdata from '../../element/dingweiList.js'
	//展开仓库值
	import {mapState} from 'vuex'
	//顶部消息提示插件
	 import HMmessages from "@/components/HM-messages/HM-messages.vue"
	 //引入模态框
	 import motai from '../../element/loadingTotal.vue'
	 
	 //引入上传提示
	 import loding from '../../element/loding.vue'
	 
	 //引入时间模块
	 var util = require('../../element/utilTime.js');
	 var time = util.formatTime(new Date());
	 
	export default{
		data(){
			return{
				num:0,
				travelsList:[
					{
						"Uname":"景点"
					},
					{
						"Uname":"美食"
					},
					{
						"Uname":"网红打卡"
					}
				],
				travelsIma:[], //获取图片链接
				video:'',	//获取视频链接
				disp:false,
				myaddre:'',	 //获取位置
				taber:'景点', //获取tab
				biaotiOne:'',//获取标题
				biaotiTwo:'',//获取内容
				avatarUrl:'', //用户头像
				nickName:'',//用户昵称
				openid:'',  //用户id
				upondImags:[],
			}
		},
		components:{
			HMmessages,//顶部提示
			motai,	//模态框
			loding
		},
		methods:{
			// tab栏切换
			tabshaddle(index,Uname){
				this.num = index
				this.taber = Uname
			},
			//点击上传图片拉起相册或拍照
			uploadImg(){
				uni.chooseImage({
				    count: 9, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['album'], //从相册选择
				    success: (res)=> {
						console.log(res);
						//扩展运算符，传多张可以依次展开，不然会报错
						this.travelsIma.push(...res.tempFilePaths)
				    }
				});
			},
			//删除图片
			ImageDelete(index){
				this.travelsIma.splice(index,1)
			},
			//预览图片
			preImage(index){
				let imagespack = this.travelsIma
				packmages(index,imagespack)
				.then(res=>{
					console.log(res)
				})
				.catch(err=>{
					console.log(err)
				})
			},
			// 上传视频
			uploadvideo(){
				// loading
				uni.showLoading({
					title:'上传中'
				});
				uni.chooseVideo({
					count: 1,
					sourceType: ['camera', 'album'],
					maxDuration:10,
				}).then(res=>{
					console.log(res[1].tempFilePath)
					this.video = res[1].tempFilePath
					//上传成功后显示
					this.disp = true
					//上传成功后消息提示框消失
					uni.hideLoading();
				}).catch(err=>{
					console.log(err)
				})
			},
			//删除视频
			VideoeDelete(){
				this.video = '',
				this.disp = false
			},
			
			myAddres(){
				uni.navigateTo({
					url:'../citys/citys'
				})
			},
			//点击上传提交
			submit(){
				console.log(this.taber)
				console.log(this.biaotiOne)
				console.log(this.biaotiTwo)
				console.log(this.travelsIma)
				console.log(this.video)
				console.log(this.myaddre)
				
				if(this.biaotiOne==''){
					let str = '请填写标题';
					this.total(str)
				}else if(this.biaotiTwo==''){
					let str = '请填写内容';
					this.total(str)
				}else if(this.travelsIma.length<3){
					let str = '上传的图片不少于三张';
					this.total(str)
				}else{
					console.log('ok')
					this.userinfo()
				}
			},
			//判断用户是否登录
			userinfo(){
				const db = wx.cloud.database()
				const users = db.collection('users').get()
				.then(res=>{
					console.log(res)
					if(res.data.length==0){
						console.log('没有登陆')
						this.$refs.mon.init()
					}else{
						console.log('已经登陆')
						let nick = res.data[0]
						this.avatarUrl = nick.avatarUrl
						this.nickName = nick.nickName
						this.openid = nick._openid
						// console.log(this.avatarUrl,this.nickName,this.openid)
						//上传用户提交的数据到数据库
						this.userdata()
					}
				}).catch(err=>{
					console.log(err)
				})
			},
			//提示封装
			total(str){
				this.HMmessages.show(str,{icon:'error',fontColor:'#000000',background:'#f40000',iconColor:'#000000'})
			},
			//用户上传数据到数据库①await先上传图片，再await视频，再await所有
			async userdata(){
				//图片上传
				let staticimg = await this.staticimg()
				console.log(staticimg)	//打印返回来的结果
				
				this.upondImags = staticimg
				
				
				
				//视频上传
				let startvideo = await this.startvideo()
				console.log(startvideo)  //打印返回来的结果
				
				//最后将所有东西提交到数据库 
				await this.clounData(staticimg)
			},
			
			//等待图片上传的函数
			staticimg(){
				var imgfilepath =[];
				return new Promise((resolve,reject)=>{ 
					//图片不能上传一个数组 用foreach()展开
					this.travelsIma.forEach((value)=>{
						// console.log(value) 展开后的每一项
						// console.log(value) 
						//上传随机名字字符串操作
						let imgion = value.lastIndexOf('.')
						let eximg = value.slice(imgion)
						let cloundpath = `${Date.now()}${eximg}`
						
						wx.cloud.uploadFile({
							cloudPath:'ima/' + cloundpath, //上传到哪个文件夹
							filePath:value       //要上传的文件路径
						}).then(res=>{
							imgfilepath.push(res.fileID) //放到数组中一次性返回
							
							//异步问题，要判断，不然不会等待后面的图片是否返回
							if(imgfilepath.length == this.travelsIma.length){
								resolve(imgfilepath)
							}
						}).catch(err=>{
							console.log(err)
						})
					})
				})
			},
			//等待视频上传
			startvideo(){
				return new Promise((resolve,reject)=>{
					//判断用户是否上传视频
					if(this.video == ''){
						console.log('不上传视频')
						resolve('')
					}else{
						console.log('上传视频')
						//上传随机名字字符串操作
						let videoico = this.video.lastIndexOf('.')
						let exvideo = this.video.slice(videoico)
						let cloundpath = `${Date.now()}${exvideo}`
						console.log(cloundpath) 
						wx.cloud.uploadFile({
							cloudPath:'video/' + cloundpath, //上传到哪个文件夹
							filePath:this.video ,      //要上传的文件路径
						}).then(res=>{
							// console.log(res)
							resolve(res)
						}).catch(err=>{
							console.log(err)
						})
					}
				})
			},
			
			//最后将所有东西提交到数据库
			clounData(upondImags){
				//以对象的新式把所有数据一并提交到数据库
				let datas = {
					travelsIma:upondImags, //提交图片链接
					video:this.video,		//提交视频链接					
					myaddre:this.myaddre,	//提交位置		
					taber:this.taber,		//提交tab		
					biaotiOne:this.biaotiOne,	//提交标题	
					biaotiTwo:this.biaotiTwo,	//提交内容
					avatarUrl:this.avatarUrl, 	//用户头像
					nickName:this.nickName,		//用户昵称
					openid:this.openid,  		//用户id
					time:time		//提交时间
				};
				//操作数据库
				const db = wx.cloud.database();
				db.collection('userdata').add({
				  // data 字段表示需新增的 JSON 数据
				  data: {
					datainfo:datas
				  }
				}).then(res => {
				  console.log(res)
				  
				  //发表后跳转
				  uni.switchTab({
				  	url:'../strategy/strategy'
				  })
				  
				  //发表成功页面不跟新所以传值给vuex让computed属性监听
				  let pagesis = true
				  this.$store.commit("roturnMuta",pagesis)
				  
				}).catch(err=>{
					console.log(err)
				})
			}
		},
		
		created() {
			//当前发表旅游定位定位
			addresdata().then(res=>{
				// console.log(res.result.address_component.city)
				this.myaddre = res.result.address_component.city
			}).catch(err=>{
				console.log(err)
				this.myaddre = '北京'
			})
		},
		computed:{
			...mapState(['travecity']),
			count(){
				console.log(this.travecity.traveing)
				this.myaddre = this.travecity.traveing
			},
			
		}
	}
</script>

<style lang="scss">
	.travels-wrap{
		padding: 20upx 25upx;
		.travels{
			display: flex;
			justify-content: start;
			align-items: center;
			text{
				font-size: 32upx;
				font-weight: bold;
				margin-right: 20upx;
			}
			view{
				background-color: #f3f3f3;
				padding: 10upx 20upx;
				margin: 0 20upx;
				border-radius: 16upx;
				color: #616161;
			}
		}
		.input-title{
			height: 60upx;
			width: 100%;
			margin: 30upx 0;
			border-bottom: 1px solid #e5e1d5 ;
			input{
				width: 100%;
				height: 100%;
			}
		}
		.input-neiron{
			width: 100%;
			height: 300upx;
			border-bottom: 1px solid #e5e1d5 ;
			textarea{
				width: 100%;
				height: 100%;
			}
		}
	}
	.active{
		background-color: #fff231!important;
		color: #2d1806!important;
	}
	.travels-upload{
		.uploadImgsDelete{
			position: absolute;
			top: 10upx;
			right: 5upx;
			width: 50upx;
			height: 50upx;
			
		}
		.upload-img{
			width: 160upx;
			height: 160upx;
			padding: 10upx 25upx;
			image{
				border-radius: 10upx;
				width: 100%;
				height: 100%;
			}
		}
		.upload-images-night{
			display: flex;
			flex-wrap: wrap;
			padding: 10upx;
			box-sizing: border-box;
			justify-content: start;
			
			.uploadImgs{
				margin: 20upx 10upx;
				width: 220upx;
				height: 220upx;
				border-radius: 10upx;
			}
		}
	}
	
	.video-wrap{
		view{
			width: 160upx;
			height: 160upx;
			padding: 10upx 25upx;
			image{
				border-radius: 10upx;
				width: 100%;
				height: 100%;
			}
		}
	}
	.video-m{
		position: relative;
		width: 100%;
		height: 420upx;
		video{
			width: 100%;
			height: 100%;
		}
	}
	.uploadVideoDelete{
		position: absolute;
		top: -3upx;right: -3upx;
		width: 60upx;
		height: 60upx;
	}
	
	
	.city-view{
		width: 100%;
		height: 100upx;
		background-color: #f1f1f1;
		padding-left: 20upx;
		margin-top: 20upx;
		margin-bottom: 150upx;
		display: flex;
		justify-content: start;
		align-items: center;
		.city-img{
			margin-left: 20upx;
			display: flex;
			justify-content: start;
			align-items: center;
			.txt{
				color: #11ff11;
				margin-left: 10upx;
			}
			image{
				width: 60upx;
				height: 60upx;
			}
		}
		
	}
	
	.fabu-btn{
		position: fixed;
		bottom: 0; left:0;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 110upx;
		background-color: #951cff;
		text{
			color: #ffffff;
			font-size: 40upx;
			
		}
	}
</style>
